package com.tusuo.stds.ui.gender;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SetGenderPresenter.class)
class SetGenderPresenter extends MvpBasePresenter<SetGenderView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mSetGenderSubscriber = null;

    SetGenderPresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initSetGenderPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mSetGenderSubscriber != null) {
            mSetGenderSubscriber.unsubscribe();
            mSetGenderSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    void setGender(int gender) {
        mSetGenderSubscriber = new SetGenderSubscriber(gender);
        mApiHelper.setGender(mSetGenderSubscriber, gender);
    }

    private class SetGenderSubscriber extends Subscriber<ApiResult> {

        private int mGender;

        SetGenderSubscriber(int mGender) {
            this.mGender = mGender;
        }

        @Override
        public void onCompleted() {
            getView().updateGenderView(mGender);
        }

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (result.checkState(mContext)) {
                Utils.UI.showToastShort("设置成功");
                if (getView() != null) {
                    getView().backToMainPage();
                }
            }
        }
    }
}
